var mongoose = require('mongoose');
var Comment = require("../models/mod_comment");
var Users = require("../models/mod_user");
var rc4=require("../models/mod_password");

//新增
exports.comment_create = function (req, res, next) {
    const person_name=JSON.parse(rc4(req.body.person_name));
    req.body.person_name=person_name;
    const comment = new Comment(req.body);

    comment.save().then((data) => {
        res.json(data);
    }).catch(err => res.json(err));
}
//修改
exports.comment_update = function (req, res, next) {
    const id = req.params.id;
    Comment.findByIdAndUpdate(id, { $set: req.body }, { new: true }).then(data => {
        res.json(data);
    });
}
//删除一个
exports.comment_delete = function (req, res, next) {
    const id = req.params.id;
    Comment.findByIdAndDelete(id).then(data => {
        res.json(data);
    });
}
//删除多个
exports.comment_removes = function (req, res, next) {
    const ids = req.body.ids.split(",");
    Comment.remove({ _id: { $in: ids } }).then(data => {
        res.json(data);
    });
}
//查询指定数据
exports.comment_list_id = function (req, res, next) {
    const id = req.params.id;
    Comment.findById(id).then(data => {
        res.json(data);
    });
}
//查询所有（分页）
exports.comment_list = function (req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;
    var search = req.body.search ? req.body.search : '';
    var ids = req.body.ids ? req.body.ids : '';

    var options = {
        page: +page,
        limit: +rows,
        sort: { _id: -1 }
    }



    var queryparams={};
    if(req.body.search&&search.length>0){
        Users.find({username:search}).then(data => {
            // console.log(data[0]._id);
            queryparams={
                $or: [
                    {"_id":data[0]._id},
                    {"source":new RegExp(search,'i')}
                ]
            }
            console.log(queryparams);
            
        });
    }

    console.log(queryparams);
    if(req.body.ids&&ids.length>0){
        const ids = req.body.ids.split(",");
        //深拷贝，条件叠加
        queryparams=Object.assign(queryparams,{
            type: { $in: ids }
        })
    }

    Comment.paginate(queryparams, options, function (err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}